<template>
  <el-dialog
    title="分配权限"
    :visible.sync="dialogVisibleRightsRoleEdit"
    :before-close="closedDialog"
  >
    <el-tree
      :data="treeData"
      show-checkbox
      node-key="id"
      :default-expanded-keys="nodeList"
      :default-checked-keys="checkedNodeList"
      :props="defaultProps"
      ref="refTree"
    >
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closedDialog">取 消</el-button>
      <el-button type="primary" @click="submitDialog">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    dialogVisibleRightsRoleEdit: {
      type: Boolean,
      default: false
    },
    roleInfo: {
      type: Object,
      default() {
        return {
          children: []
        }
      }
    }
  },
  data() {
    return {
      formLabelWidth: '120px',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkedNodeList: []
    }
  },
  computed: {
    // 所有节点数组
    nodeList() {
      const tempArr = []
      this.treeData.forEach((item1) => {
        tempArr.push(item1.id)
        item1.children.forEach((item2) => {
          tempArr.push(item2.id)
          item2.children.forEach((item3) => {
            tempArr.push(item3.id)
          })
        })
      })
      return tempArr
    }
  },

  // 监控，当传过来的 roleinfo 变化时，改变数据
  watch: {
    roleInfo(infoObj) {
      const tempArr = []
      infoObj.children.forEach((item1) => {
        item1.children.forEach((item2) => {
          item2.children.forEach((item3) => {
            tempArr.push(item3.id)
          })
        })
      })
      this.checkedNodeList = tempArr
      this.$nextTick(() => {
        this.$refs.refTree.setCheckedKeys(tempArr)
      })
    }
  },
  created() {
    this.getRightListData()
  },

  methods: {
    async getRightListData() {
      const {
        data: { data, meta }
      } = await this.$http.get('/rights/tree')

      if (meta.status === 200) {
        this.treeData = data
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    closedDialog() {
      this.$emit('editRightsRoleClosed')
    },
    async submitDialog() {
      // 获取全选节点
      const fullCheckedArr = this.$refs.refTree.getCheckedKeys()
      // 获取半选节点
      const halfCheckedArr = this.$refs.refTree.getHalfCheckedKeys()

      const rids = [...fullCheckedArr, ...halfCheckedArr].join()
      console.log(rids)

      const {
        data: { meta }
      } = await this.$http.post(`roles/${this.roleInfo.id}/rights`, {
        rids
      })
      if (meta.status === 200) {
        // 修改成功后，关闭对话框，更新 users 页码表格数据
        this.$message.success(meta.msg)
        this.$emit('editRightsRoleClosed')
        this.$emit('editRightsRoleSuccess')
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style></style>
